
import { Notification } from 'element-ui'
import { parseTime } from '@/utils'
import store from '@/store'
/**
 * 工具类
 */
export const tableInfo = {
  tableKey: 0,
  loading: false,
  list: null,
  total: 0,
  listLoading: true,
  queryParams: {
    page: 1,
    limit: 20
  },
  importanceOptions: [1, 2, 3],
  sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
  statusOptions: ['published', 'draft', 'deleted'],
  showReviewer: false,
  dialogFormVisible: false,
  dialogStatus: '',
  textMap: { update: '编辑', create: '新增' },
  dialogPvVisible: false,
  pvData: [],
  rules: {
    type: [{ required: true, message: 'type is required', trigger: 'change' }],
    timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
    title: [{ required: true, message: 'title is required', trigger: 'blur' }]
  },
  downloadLoading: false
}

var crudMethods = {
  // 列表获取
  getList: function(that, fetchListFun) {
    that.listLoading = true
    fetchListFun(that.queryParams).then(response => {
      that.list = response.data.records
      that.total = response.data.total
      setTimeout(() => { that.listLoading = false }, 1.5 * 1000)
    })
  },
  // 查询方法
  handleFilter(that, fetchListFun) {
    that.queryParams.page = 1
    crudMethods.getList(that, fetchListFun)
  },
  // 新增页面
  handleCreate(that) {
    crudMethods.resetTemp(that)
    that.dialogStatus = 'create'
    that.dialogFormVisible = true
    that.$nextTick(() => {
      that.$refs['dataForm'].clearValidate()
    })
  },
  // 新增确定
  createData(that, createFun) {
    that.$refs['dataForm'].validate((valid) => {
      if (valid) {
        createFun(that.temp).then(() => {
          that.list.unshift(that.temp)
          that.dialogFormVisible = false
          Notification({ title: 'Success', message: '操作成功', type: 'success', duration: 2000 })
        })
      }
    })
  },
  // 新增确定
  createDataSingle(that, createFun,callback) {
    that.$refs['dataForm'].validate((valid) => {
      if (valid) {
        createFun(that.temp).then(() => {
          Notification({ title: 'Success', message: '操作成功', type: 'success', duration: 2000 })
          that.$refs['dataForm'].resetFields()
          that.loading = false
          callback()
        })
      }else{
        return false;
      }
    })
  },
  // 更新页面
  handleUpdate(that, row) {
    that.temp = Object.assign({}, row) // copy obj
    that.temp.timestamp = new Date(that.temp.timestamp)
    that.dialogStatus = 'update'
    that.dialogFormVisible = true

    that.$nextTick(() => { that.$refs['dataForm'].clearValidate() })
  },
  // 更新确认
  updateData(that, updateFun) {
    that.$refs['dataForm'].validate((valid) => {
      if (valid) {
        const tempData = Object.assign({}, that.temp)
        updateFun(tempData[that.idKey], tempData).then(() => {
          const index = that.list.findIndex(v => v[that.idKey] === that.temp[that.idKey])
          that.list.splice(index, 1, that.temp)
          that.dialogFormVisible = false
          Notification({ title: 'Success', message: '操作成功', type: 'success', duration: 2000 })
        })
      }
    })
  },
  // 更新确认
  updateDataSingle(that, updateFun) {
    that.$refs['dataForm'].validate((valid) => {
      if (valid) {
        const tempData = Object.assign({}, that.temp)
        updateFun(tempData[that.idKey], tempData).then(() => {
          Notification({ title: 'Success', message: '操作成功', type: 'success', duration: 2000 })
        })
      }else{
        return false;
      }
    })
  },
  // 删除方法
  handleDelete(that, row, index, deleteFun) {
    deleteFun(row[that.idKey]).then(() => {
      Notification({ title: 'Success', message: '操作成功', type: 'success', duration: 2000 })
      that.list.splice(index, 1)
    })
  },
  handleModifyStatus(row, status) {
    this.$message({
      message: '操作Success',
      type: 'success'
    })
    row.status = status
  },
  sortChange(data) {
    const { prop, order } = data
    if (prop === 'id') {
      this.sortByID(order)
    }
  },
  sortByID(order) {
    if (order === 'ascending') {
      this.queryParams.sort = '+id'
    } else {
      this.queryParams.sort = '-id'
    }
    this.handleFilter()
  },
  resetTemp(that) {
    that.temp = {
      userId: undefined,
      status: null,
      nickname: '',
      channelId: null,
      cellphone: ''
    }
  }

}

var utilMethods = {
  optionsReduce(typeOptions) {
    const typeKeyValue = typeOptions.reduce((acc, cur) => {
      acc[cur.key] = cur.display_namez
      return acc
    }, {})
    return typeKeyValue
  },
  success() {
    Notification({ title: '成功', message: '操作成功', type: 'success', duration: 2000 })
  },
  // 导出Excel
  formatJson(list, filterVal) {
    return list.map(v => filterVal.map(j => {
      if (j === 'timestamp') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
    }))
  }
}

var sortMethods = {
  getSortClass: function(key) {
    const sort = this.queryParams.sort
    return sort === `+${key}` ? 'ascending' : 'descending'
  }
}
export const crudUtil = {
  tableInfo: tableInfo,
  getList: crudMethods.getList,
  handleCreate: crudMethods.handleCreate,
  createData: crudMethods.createData,
  createDataSingle: crudMethods.createDataSingle,
  handleFilter: crudMethods.handleFilter,
  handleUpdate: crudMethods.handleUpdate,
  updateData: crudMethods.updateData,
  updateDataSingle: crudMethods.updateDataSingle,
  handleDelete: crudMethods.handleDelete
}

export const toolUtil = {
  optionsReduce: utilMethods.optionsReduce,
  success: utilMethods.success,
  formatJson: utilMethods.formatJson
}

export const sortUtil = {
  getSortClass: sortMethods.getSortClass,
  sortChange: crudMethods.sortChange
}


export function getMpAppid() {
  return store.state.wxAccount.currentItem.appid
}

